<?php

/**
 * Jelszóemlékeztető oldal generálása
 *
 * @author poli
 */
class LostPasswordPageGenerator extends BaseContentGenerator {

	private $_initialized = false;

	public function LostPasswordPageGenerator($context, $generatorId, $iniParams = null, $skipIniParamsUpdateFromRequest = false) {
		parent::BaseContentGenerator("LostPasswordPage", $context, $generatorId, $iniParams, $skipIniParamsUpdateFromRequest);
	}

	/**
	 * Mi most használjuk az iniParams tömbünket nagyon is! Úhygogy nosza, dolgozzuk fel
	 * belőle a dolgokat!
	 *
	 * @see site/contentGenerators/BaseContentGenerator#processSavedIniParams()
	 */
	public function processSavedIniParams($savedIniParams) {
		$this->_iniParams = $savedIniParams;
	}

	protected function _init() {			
		if($this->_initialized) return;
		$this->_initialized = true;			
	}


	public function serveRequest() {
		parent::serveRequest();

		$this->_init();

		SiteBase::setPageTitle(TextHandler::getText('lpp_pageTitle'));

		$action = FunctionLibrary::getGetOrPostValueSmart('action', null);
		if(!is_null($action)) {
			$action = 'action_'.$action;
			$this->$action();
		}

		$tpl = BaseContentGenerator::loadTemplateFile("lost_password_page.tpl.html");
			
		TextHandler::insertTextsIntoTemplate($tpl, null, 'lpp_');
		TextHandler::insertTextsIntoTemplate($tpl, null, 'gen_');
		$tpl->setVariable('app_root_url', APP_ROOT_URL);

		$tpl->setVariable('link_form', UrlUtil::getRequestUrl());

		return $tpl->get();
	}

	protected function action_sendPassword() {
		$redirectUrl = UrlUtil::getRequestUrl();
			
		$email = FunctionLibrary::getPostValueSmart("email", "");

		if(TextUtil::isStringEmpty($email)) {
			handleError(TextHandler::getText('lpp_empty_email'), $redirectUrl);
			exit();
		}
		if(!FunctionLibrary::checkEmailSyntax($email)) {
			handleError(TextHandler::getText('lpp_wrong_email'), $redirectUrl);
			exit();
		}

		// na nézzük megleljük-e!
		try {
			$user = SiteUser::getUserWithEmail($email);
		} catch (Exception $e) {
			$user = null;
		}
			
		if(is_null($user)) {
			handleError(TextHandler::getText('lpp_notfound'), $redirectUrl);
			exit();
		}

		// oké, mehet neki a mail!
		$globalVariables = SiteAlertHandler::getGlobalVariables();
		SiteAlertHandler::addUserVariables($globalVariables, $user);

		$admins = array($user);
		$recipients = SiteAlertHandler::createEmailRecipients($admins);
		SiteAlertHandler::sendEmailAlert("password_reminder.tpl.email", $recipients, $globalVariables);

		if($user->getType() == SiteUser::TYPE_NEWREG) {
			handleSuccess(TextHandler::getText('lpp_success'), $redirectUrl);
		} else {
			handleSuccess(TextHandler::getText('lpp_success'), $redirectUrl);
		}
		exit();
	}

}
?>